﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ReLogic.Content;
using Terraria;
using Terraria.Audio;
using Terraria.GameContent;
using Terraria.ID;
using Terraria.UI;

namespace WorseGame.Common.UIs.Elements
{
  
    public class CrateIcon : UIElement {
      
        public bool barOverCrate;

        public bool crateCaught;

    
        public bool isAppearing;

        public float iconScale = 0.6f;

    
        private HorizontalProgressBar _catchProgressBar;

        private readonly Asset<Texture2D> _crateSprite;

        private readonly Item _crateItem;

        public CrateIcon() {
            Main.instance.LoadItem(ItemID.WoodenCrate);
            _crateSprite = TextureAssets.Item[ItemID.WoodenCrate];

            Width.Set(_crateSprite.Width(), 0f);
            Height.Set(_crateSprite.Height(), 0f);

            _crateItem = new Item(ItemID.WoodenCrate);

            _catchProgressBar = new HorizontalProgressBar(0f, false) {
                HAlign = 0.5f
            };
            _catchProgressBar.Width.Set(Width.Pixels * 1.5f, 0f);
            _catchProgressBar.Height.Set(10f, 0f);
            _catchProgressBar.Top.Set(-10f, 0f);
            Append(_catchProgressBar);
        }

        public override void Update(GameTime gameTime) {
            base.Update(gameTime);

            if (isAppearing) {
                if ((iconScale += 5f / 60f) >= 1f) {
                    iconScale = 1f;
                    isAppearing = false;
                }
            }

            if (crateCaught) {
                return;
            }

            float positiveRateOfChange = 0.45f / 60f;
        
            float negativeRateOfChange = -0.6f / 60f;

            _catchProgressBar.percentProgress = MathHelper.Clamp(_catchProgressBar.percentProgress + (barOverCrate ? positiveRateOfChange : negativeRateOfChange), 0f, 1f);
            if (_catchProgressBar.percentProgress >= 1f) {
                crateCaught = true;

                SoundEngine.PlaySound(SoundID.Coins);
            }
        }

        public override void Draw(SpriteBatch spriteBatch) {
            if (!crateCaught) {
                base.Draw(spriteBatch);
            }
        }

        protected override void DrawSelf(SpriteBatch spriteBatch) {
            Vector2 shakeDisplacement = barOverCrate
                ? new Vector2(0.5f * Main.rand.NextBool().ToDirectionInt(), 0.5f * Main.rand.NextBool().ToDirectionInt())
                : Vector2.Zero;

            Main.DrawItemIcon(spriteBatch, _crateItem, GetDimensions().Center() + shakeDisplacement, Color.White, _crateSprite.Width() * iconScale);
        }
    }
}